
package com.itheima.tanhua.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.itheima.tanhua.api.UserInfoApi;
import com.itheima.tanhua.autoconfig.template.OssTemplate;
import com.itheima.tanhua.domain.UserInfo;
import com.itheima.tanhua.exception.BusinessException;
import com.itheima.tanhua.mongo.Acoustic;
import com.itheima.tanhua.utils.Constants;
import com.itheima.tanhua.utils.UserHolder;
import com.itheima.tanhua.vo.AcousticVo;
import com.itheima.tanhua.vo.ErrorResult;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


import cn.hutool.core.date.DateUtil;
import com.itheima.tanhua.api.AcousticApi;
import com.itheima.tanhua.api.UserInfoApi;
import com.itheima.tanhua.domain.UserInfo;
import com.itheima.tanhua.exception.BusinessException;
import com.itheima.tanhua.mongo.Acoustic;
import com.itheima.tanhua.utils.Constants;
import com.itheima.tanhua.utils.UserHolder;
import com.itheima.tanhua.vo.AcousticVo;
import com.itheima.tanhua.vo.ErrorResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author Lff
 * @date 2022/4/8
 * 查语音 接语音
 */
@Service
public class PeachblossomService {

    @Autowired
    private RedisTemplate redisTemplate;

    @DubboReference
    private AcousticApi acousticApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    /**
     * 接收语音
     *
     * @return
     */
    public AcousticVo getPeachblossomOne() {
        if (!redisTemplate.hasKey(Constants.PEACHBLOSSOM)) {
            //key不存在 创建并设置 过期时间
            //设置过期时间
            //获取当前时间到今天结束的时间
            DateTime dateTime = DateUtil.endOfDay(new Date());//今天结束时间 23:59:59 所以+1
            long seconds = (dateTime.getTime() - new Date().getTime() + 1000) / 1000;
            redisTemplate.expire(Constants.PEACHBLOSSOM, seconds, TimeUnit.SECONDS);
        }
        //调用redis检验剩余次数
        String hashKey = Constants.PEACHBLOSSOM_HASHKEY + UserHolder.getUser().getId();
        String countStr = (String) redisTemplate.opsForHash().get(Constants.PEACHBLOSSOM, hashKey);
        Integer count = 0;
        if (StringUtils.isEmpty(countStr)) {
            //看key是否有对应的值，没有初始化为9，有就-1
            //为null 代表今天第一次获取 次数为 9
            count = 9;
        } else {
            count = Integer.valueOf(countStr) - 1;
            if (count < 0) {
                //超过最大限制
                throw new BusinessException(ErrorResult.maximumError());
            }
        }
        //调用api随机获取一个语音
        List<Acoustic> acoustics = acousticApi.findAcousticRandom(UserHolder.getUser().getId(), 1);
        if(CollUtil.isEmpty(acoustics)){
            //没查到
            throw new BusinessException(ErrorResult.builder().errMessage("暂时没有更多了呢。。").build());
        }
        //抽取语音所属人id

        Acoustic acoustic = acoustics.get(0);
        Long userId = acoustic.getUserId();
        //根据id查询UserInfo
        UserInfo userInfo = userInfoApi.findById(userId);
        //修改acoustic
        acoustic.setPickupDateTime(System.currentTimeMillis());//拾取时间
        acoustic.setPickupUserId(userId);//拾取人
        acoustic.setPickup(true);//是否被拾取
        acousticApi.updateById(acoustic);//修改
        //填充vo
        AcousticVo result = AcousticVo.init(userInfo, acoustic, count);
        //修改redis数据
        redisTemplate.opsForHash().put(Constants.PEACHBLOSSOM, hashKey, count.toString());
        //返回数据
        return result;
    }

    //发送
    public void sendVoice(MultipartFile soundFile) throws IOException {
        //1.判断是否为空
        if (soundFile == null) {
            throw new BusinessException(ErrorResult.builder().errMessage("文件为空").build());
        }
        //2.进行文件上传,上传到阿里云oss上
        String voicePath = ossTemplate.upload(soundFile.getOriginalFilename(), soundFile.getInputStream());
        //3.将路径保存到Mongo中
        Acoustic acoustic = new Acoustic();
        acoustic.setUserId(UserHolder.getUser().getId());
        acoustic.setSoundUrl(voicePath);
        acoustic.setCreated(System.currentTimeMillis());
        acousticApi.saveSound(acoustic);
    }
}

